import { createSlice, createEntityAdapter, createSelector } from '@reduxjs/toolkit'
import * as songOp from '../../config/playList.js'
const songInfoAdapter = createEntityAdapter({
    loading: 'idle',
}, localStorage.getItem('playlist') || []);

export const playListSlice = createSlice({
    name: 'playlist',
    initialState: {
        playlist: songInfoAdapter.getInitialState(),
        playlistType: null,
        playlistId: null
    },
    reducers: {
        [songOp.CHANGE_PLAYING_SONG_INDEX]: (state, action) => {
            const {
                prePlayingIndex,
                currentPlayIndex
            } = action.payload;
            if (prePlayingIndex !== undefined && prePlayingIndex != -1) {
                state.playlist.entities[prePlayingIndex].playing = false;
            }
            if (state.playlist.entities[currentPlayIndex]) {
                state.playlist.entities[currentPlayIndex].playing = true;
            }
            console.log(state.playlistType)

        },
        [songOp.DELETE_OPERATION]: (state, action) => {
            songInfoAdapter.removeOne(state.playlist, action.payload.deleteId)
        },
        [songOp.CHANGE_OPERATION]: {
            reducer(state, action) {
                const songInfo = action?.payload?.playlist?.map((_payload) => {
                    return {
                        name: _payload?.title || _payload?.name,
                        musicSrc: _payload?.audioSrc || _payload?.musicSrc,
                        cover: _payload?.src || _payload?.cover,
                        singer: _payload?.artist || _payload?.singer,
                        id: _payload?.id,
                        playing: state?.playlist?.entities?.[_payload.id]?.playing
                    }
                })
                songInfoAdapter.setAll(state.playlist, songInfo);
                state.playlistId = action.payload.playlistId;
                state.playlistType = action.payload.playListType;

            }
        },
        [songOp.UNSHIFT_OPERATION]: (state, action) => {
        },
    },
})
export const {
    selectAll: selectAllSongs, selectById: selectSongById
} = songInfoAdapter.getSelectors(state => state.playlist.playlist)
export const selectPlayListId = state => state?.playlist?.playlistId;
export const selectPlayListType = state => state?.playlist?.playlistType;
export const findPlayingId = createSelector(selectAllSongs, (allsongs) => {
    return allsongs[allsongs.findIndex((obj) => obj.playing)]?.id
})
export const checkSongInfoPlayList = createSelector(selectSongById, (songInfo) => {
    return Boolean(songInfo)
})
// Action creators are generated for each case reducer function
export const { deleteSong, changePlaylist, unshiftSong, changePlayingSongIndex } = playListSlice.actions;
export default playListSlice.reducer;